/*
 * Copyright 2018 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.drools.workbench.screens.scenariosimulation.client.commands.actualcommands;

import org.drools.scenariosimulation.api.model.FactMappingValueType;
import org.drools.workbench.screens.scenariosimulation.client.commands.ScenarioSimulationContext;
import org.drools.workbench.screens.scenariosimulation.client.enums.GridWidget;
import org.drools.workbench.screens.scenariosimulation.client.widgets.ScenarioGridColumn;
import org.uberfire.ext.wires.core.grids.client.model.GridData;

/**
 * <code>Command</code> to <b>insert</b> a column.
 */
public class InsertColumnCommand extends AbstractSelectedColumnCommand {

    public InsertColumnCommand(GridWidget gridWidget) {
        super(gridWidget, FactMappingValueType.NOT_EXPRESSION);
    }

    @Override
    protected void executeIfSelectedColumn(ScenarioSimulationContext context, ScenarioGridColumn selectedColumn) {
        /* Here, it calculates the position where the column will be added, according to the selected column position,
           if it should be added in the right or on the left of the selected position and if is a property (i.e. is a new
           property column which have to be added on the same instance group of the selected one */
        int columnPosition;
        if (context.getStatus().isAsProperty()) {
            columnPosition = context.getStatus().isRight() ? context.getStatus().getColumnIndex() + 1 : context.getStatus().getColumnIndex();
        } else {
            GridData.Range instanceRange = context.getAbstractScesimGridModelByGridWidget(gridWidget).getInstanceLimits(context.getStatus().getColumnIndex());
            columnPosition = context.getStatus().isRight() ? instanceRange.getMaxRowIndex() + 1 : instanceRange.getMinRowIndex();
        }
        boolean cloneInstance = context.getStatus().isAsProperty() && selectedColumn.isInstanceAssigned();

        insertNewColumn(context, selectedColumn, columnPosition, cloneInstance);
    }
}
